package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author xudengfeng
 * @date 2020/12/5 22:40
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(String[].class)
public class StringArrayTypeHandler implements TypeHandler<String[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(i, value);
    }

    /**
     * @param resultSet 查询的结果
     * @param s         查询的列名
     * @return
     * @throws SQLException
     */
    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, String s) throws SQLException {
        //通过列名拿到结果
        String string = resultSet.getString(s);
        String[] strings = objectMapper.readValue(string, String[].class);
        return strings;
    }

    @Override
    public String[] getResult(ResultSet resultSet, int i) throws SQLException {
        return new String[0];
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        return new String[0];
    }
}
